package middlewareorid.ui;

import middlewareorid.engine.BlogsEngine;
import middlewareorid.engine.Config;
import middlewareorid.engine.HTMLConnect;
import waba.fx.Color;
import waba.fx.Font;
import waba.fx.Rect;
import waba.io.Catalog;
import waba.sys.Settings;
import waba.sys.Vm;
import waba.ui.Container;
import waba.ui.ListBox;
import waba.ui.MessageBox;
import waba.util.Vector;

public class ListCategoryWindow extends Container {

	Font font = new Font("SW", Font.PLAIN, 10);
	ListBox lbCategory = new ListBox();
	Catalog c;
	int paramLength = 50;

	public ListCategoryWindow(Rect rect) {
		setRect(rect);
		setBackColor(Color.WHITE);
		add(lbCategory);
		lbCategory.setRect(LEFT + 5, TOP + 5, getClientRect().width-10, getClientRect().height-10);
		init();
		list();
	}

	private void list() {
		/*
		 * Get data from url
		 */
		try {
			c = new Catalog("djokdja_category.Crtr.Type",Catalog.CREATE);
			HTMLConnect con = new HTMLConnect();
			con.setURL(BlogsEngine.getURLforCategoryList());
			String url_data = con.getURLData();
			if (!url_data.equals("")) {
				Vector v = con.getListItem(url_data);
				String datas[] = (String[]) v.toObjectArray();
				for (int i = 0; i < datas.length; i++) {
					lbCategory.insert(initConfigValue(datas[i]), i);
					c.addRecord(initConfigValue(datas[i]).length());
					c.writeBytes(initConfigValue(datas[i]).getBytes(), 0, paramLength);
				}	
			}
			c.close();
		} catch (Exception e) {
			new MessageBox("Error", "Error contacting web-logs ...").popupModal();
		}
	}
	
	public void init() {
		/*
		 * Init category catalog, delete it first
		 */
		c = new Catalog("djokdja_category.Crtr.Type",Catalog.READ_WRITE);
		if (c.isOpen())
		{
			c.delete();
		}
		c.close();
		Vm.debug(Settings.dataPath);		
	}	

	private String initConfigValue(String value) {
		String result = " ";
		for (int i=0; i<paramLength; i++) {
			result = result + " ";
		}
		result = (value.trim() + result).substring(0,paramLength);		
		return result;		
	}
	
	public void setStyle(int style) {
		setBackColor(Config.background[style]);
	}
}
